package com.example.mq.mqserver;

import com.example.mq.common.Consumer;
import com.example.mq.common.MqException;
import com.example.mq.mqserver.core.*;
import com.example.mq.mqserver.datacenter.DiskDataCenter;
import com.example.mq.mqserver.datacenter.MemoryDataCenter;
import lombok.Data;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2023-10-04
 * Time: 16:51
 */
/*
 * 通过这个类，来表示虚拟主机
 * 每个虚拟主机下面都管理着自己的交换机，队列，绑定，消息
 * 同时提供 api 供上层调用
 * 针对 VirtualHost 这个类，作为业务逻辑的整合者，需要对代码中抛出的异常进行处理
 */
@Data
public class VirtualHost {
    private String virtualHostName;
    private MemoryDataCenter memoryDataCenter = new MemoryDataCenter();
    private DiskDataCenter diskDataCenter = new DiskDataCenter();
    private Router router = new Router();
    private ConsumerManager consumerManager = new ConsumerManager(this);
    // 操作交换机的锁对象
    private final Object exchangeLocker = new Object();
    // 操作队列的锁对象
    private final Object queueLocker = new Object();

    public VirtualHost(String name) {
        this.virtualHostName = name;
        // 对于 memoryDataCenter 来说，不需要额外的初始化操作，只要对象 new 出来即可
        // 但是，针对 diskDataCenter 来说，则需要进行初始化操作，数据的建表和初始数据的设定
        diskDataCenter.init();
        // 还需要针对硬盘的数据，进行恢复到内存
        try {
            memoryDataCenter.recovery(diskDataCenter);
        } catch (IOException | ClassNotFoundException | MqException e) {
            e.printStackTrace();
            System.out.println("[VirtualHost] 恢复内存数据失败！");
        }
    }


    /* 创建交换机
     * 如果交换机不存在，就创建，存在，就直接返回
     * 返回值 true，创建成功，false，创建失败
     */
    public boolean exchangeDeclare(String exchangeName, ExchangeType exchangeType, boolean durable,
                                   boolean autoDelete, Map<String, Object> arguments) {
        // 把交换机的名字加上虚拟主机的名字作为前缀（区分同名的交换机）
        exchangeName = virtualHostName + exchangeName;
        try {
            synchronized (exchangeLocker) {
                // 1. 判断交换机是否存在
                Exchange existExchange = memoryDataCenter.getExchange(exchangeName);
                if (existExchange != null) {
                    // 该交换机已经存在
                    System.out.println("[VirtualHost] 交换机已经存在！exchangeName=" + exchangeName);
                    return true;
                }
                // 2. 真正创建交换机，先构造 Exchange
                Exchange exchange = new Exchange();
                exchange.setName(exchangeName);
                exchange.setType(exchangeType);
                exchange.setDurable(durable);
                exchange.setAutoDelete(autoDelete);
                exchange.setArguments(arguments);
                // 3. 把交换机对象写入硬盘
                if (durable) {
                    diskDataCenter.insertExchange(exchange);
                }
                // 4. 把交换机写入内存
                memoryDataCenter.insertExchange(exchange);
                System.out.println("[VirtualHost] 交换机创建成功！exchangeName=" + exchangeName);
            }
            return true;
        }catch (Exception e) {
            System.out.println("[VirtualHost] 交换机创建失败！exchangeName=" + exchangeName);
            e.printStackTrace();
            return false;
        }
    }

    // 删除交换机
    public boolean exchangeDelete(String exchangeName) {
        exchangeName = virtualHostName + exchangeName;
        try {
            synchronized (exchangeLocker) {
                //1. 先找到对应的交换机
                Exchange toDelete = memoryDataCenter.getExchange(exchangeName);
                if (toDelete == null) {
                    throw new MqException("[VirtualHost] 交换机不存在，无法删除！");
                }
                // 2. 删除硬盘上的交换机
                if (toDelete.isDurable()) {
                    diskDataCenter.deleteExchange(exchangeName);
                }
                // 3. 删除内存上的交换机
                memoryDataCenter.deleteExchange(exchangeName);
                System.out.println("[VirtualHost] 交换机删除成功！exchangeName=" + exchangeName);
            }
            return true;
        } catch (MqException e) {
            System.out.println("[VirtualHost] 交换机删除失败！exchangeName=" + exchangeName);
            e.printStackTrace();
            return false;
        }
    }

    // 创建队列
    public boolean queueDeclare(String queueName, boolean durable, boolean exclusive, boolean autoDelete,
                                Map<String, Object> arguments) {
        queueName = virtualHostName + queueName;
        try {
            synchronized (queueLocker) {
                // 1. 判定队列是否存在
                MSGQueue existQueue = memoryDataCenter.getQueue(queueName);
                if (existQueue != null) {
                    System.out.println("[VirtualHost] 队列已经存在！queueName=" + queueName);
                    return true;
                }
                // 2. 创建队列对象
                MSGQueue queue = new MSGQueue();
                queue.setName(queueName);
                queue.setDurable(durable);
                queue.setExclusive(exclusive);
                queue.setAutoDelete(autoDelete);
                queue.setArguments(arguments);
                // 3. 写硬盘
                if (durable) {
                    diskDataCenter.insertQueue(queue);
                }
                // 4. 写内存
                memoryDataCenter.insertQueue(queue);
                System.out.println("[VirtualHost] 队列创建成功！queueName=" + queueName);
            }
            return true;
        } catch (IOException e) {
            System.out.println("[VirtualHost] 队列创建失败！queueName=" + queueName);
            e.printStackTrace();
            return false;
        }
    }

    // 删除队列
    public boolean queueDelete(String queueName) {
        queueName = virtualHostName + queueName;
        try {
            synchronized (queueLocker) {
                // 1. 根据队列名字，查询当前队列对象
                MSGQueue queue = memoryDataCenter.getQueue(queueName);
                if (queue == null) {
                    throw new MqException("[VirtualHost] 队列不存在！无法删除！queueName=" + queueName);
                }
                // 2. 删除硬盘数据
                if (queue.isDurable()) {
                    diskDataCenter.deleteQueue(queueName);
                }
                // 3. 删除内存数据
                memoryDataCenter.deleteQueue(queueName);
                System.out.println("[VirtualHost] 删除队列成功！queueName=" + queueName);
            }
            return true;
        } catch (Exception e) {
            System.out.println("[VirtualHost] 删除队列失败！queueName=" + queueName);
            e.printStackTrace();
            return false;
        }
    }

    // 创建绑定
    public boolean queueBind(String queueName, String exchangeName, String bindingKey) {
        queueName = virtualHostName + queueName;
        exchangeName = virtualHostName + exchangeName;
        try {
            synchronized (exchangeLocker) {
                synchronized (queueLocker) {
                    // 1. 判定当前的绑定是否存在
                    Binding existBinding = memoryDataCenter.getBinding(exchangeName, queueName);
                    if (existBinding != null) {
                        throw new MqException("[VirtualHost] binding 已经存在！queueName=" + queueName + "，exchangeName=" + exchangeName);
                    }
                    // 2. 验证 bindingKey 是否合法
                    if (!router.checkBindingKey(bindingKey)) {
                        throw new MqException("[VirtualHost] bindingKey 非法！bindingKey=" + bindingKey);
                    }
                    // 3. 创建 binding 对象
                    Binding binding = new Binding();
                    binding.setExchangeName(exchangeName);
                    binding.setQueueName(queueName);
                    binding.setBindingKey(bindingKey);
                    // 4. 获取对应的交换机和队列，如果交换机和队列不存在，这样的绑定也无法创建
                    MSGQueue queue = memoryDataCenter.getQueue(queueName);
                    if (queue == null) {
                        throw new MqException("[VirtualHost] 队列不存在！queueName=" + queueName);
                    }
                    Exchange exchange = memoryDataCenter.getExchange(exchangeName);
                    if (exchange == null) {
                        throw new MqException("[VirtualHost] 交换机不存在！exchangeName=" + exchangeName);
                    }
                    // 5. 写入硬盘
                    if (queue.isDurable() && exchange.isDurable()) {
                        diskDataCenter.insertBinding(binding);
                    }
                    // 6. 写入内存
                    memoryDataCenter.insertBinding(binding);
                    System.out.println("[VirtualHost] 绑定创建成功！queueName=" + queueName + "，exchangeName=" + exchangeName);
                }
            }
            return true;
        } catch (Exception e) {
            System.out.println("[VirtualHost] 绑定创建失败！queueName=" + queueName + "，exchangeName=" + exchangeName);
            e.printStackTrace();
            return false;
        }
    }

    // 解除绑定
    public boolean queueUnbind(String queueName, String exchangeName) {
        queueName = virtualHostName + queueName;
        exchangeName = virtualHostName + exchangeName;
        try {
            synchronized (exchangeLocker) {
                synchronized (queueLocker) {
                    // 1. 判断 binding 是否存在
                    Binding binding = memoryDataCenter.getBinding(exchangeName, queueName);
                    if (binding == null) {
                        throw new MqException("[VirtualHost] 绑定删除失败！绑定不存在！queueName=" + queueName + "，exchangeName=" + exchangeName);
                    }
//            // 2. 获取队列和交换机
//            MSGQueue queue = memoryDataCenter.getQueue(queueName);
//            if (queue == null) {
//                throw new MqException("[VirtualHost] 队列不存在！queueName=" + queueName);
//            }
//            Exchange exchange = memoryDataCenter.getExchange(exchangeName);
//            if (exchange == null) {
//                throw new MqException("[VirtualHost] 交换机不存在！exchangeName=" + exchangeName);
//            }
//            // 3. 删除硬盘上的数据
//            if (queue.isDurable() && exchange.isDurable()) {
//                diskDataCenter.deleteBinding(binding);
//            }

            /*
               删除绑定时可能会出现问题：在删除绑定之前，先删除了交换机和队列，但是二者的绑定关系还存在，就导致绑定无法被删除（一直抛异常）
               解决方案：
               1. 参考类似 mysql 的外键（foreign key），删除队列或交换机的时候，判断是否有相关的绑定存在，如果存在必须先解除绑定，才能删除
               2. 删除绑定时不判断交换机或队列，直接删除（反正 sql 语句也无副作用）
             */


                    // 无论是否被持久化了，都尝试从硬盘中删除，即使不存在，sql 语句也没有什么副作用
                    diskDataCenter.deleteBinding(binding);

                    // 4. 删除内存的数据
                    memoryDataCenter.deleteBinding(binding);
                    System.out.println("[VirtualHost] 删除绑定成功！");
                }
            }
            return true;
        } catch (Exception e) {
            System.out.println("[VirtualHost] 删除绑定失败！");
            e.printStackTrace();
            return false;
        }
    }

    // 发送消息到指定的交换机和队列中
    public boolean basicPublish(String exchangeName, String routingKey, BasicProperties basicProperties, byte[] body) {
        try {
            // 1. 转发交换机的名字
            exchangeName = virtualHostName + exchangeName;
            // 2. 检查 routingKey 是否合法
            if (!router.checkRoutingKey(routingKey)) {
                throw new MqException("[VirtualHost] routingKey 非法！routingKey=" + routingKey);
            }
            // 3. 查找交换机对象
            Exchange exchange = memoryDataCenter.getExchange(exchangeName);
            if (exchange == null) {
                throw new MqException("[VirtualHost 交换机不存在！exchangeName=" + exchangeName);
            }
            // 4. 判断交换机的类型
            if (exchange.getType() == ExchangeType.DIRECT) {
                // DIRECT 交换机的规则：
                // 以 routingKey 作为队列的名字，直接把消息写入指定的队列
                // 即使没有绑定关系，因为指定了队列名字，也可以发送消息
                String queueName = virtualHostName + routingKey;// 指定的队列名
                // 5. 构造消息对象
                Message message = Message.createMessageWithId(routingKey, basicProperties, body);
                // 6. 查找指定的队列是否存在
                MSGQueue queue = memoryDataCenter.getQueue(queueName);
                if (queue == null) {
                    throw new MqException("[VirtualHost] 队列不存在！queueName=" + queueName);
                }
                // 7. 队列存在，发送消息
                sendMessage(queue, message);
            } else {
                // 按照 FANOUT 和 TOPIC 的方式来转发
                // 5. 找到该交换机的所有绑定，遍历这些绑定
                ConcurrentHashMap<String, Binding> bindingsMap = memoryDataCenter.getBindings(exchangeName);
                for (Map.Entry<String, Binding> entry : bindingsMap.entrySet()) {
                    // 1) 获取到绑定对象，判断队列是否存在
                    Binding binding = entry.getValue();
                    MSGQueue queue = memoryDataCenter.getQueue(binding.getQueueName());
                    if (queue == null) {
                        // 此处不抛出异常
                        // 不能因为一个队列的失败，影响后面的传输
                        System.out.println("[VirtualHost] basicPublish 发送消息时，发现队列不存在！queueName=" + binding.getQueueName());
                        continue;
                    }
                    // 2) 构造消息对象
                    Message message = Message.createMessageWithId(routingKey, basicProperties, body);
                    // 3) 判断这个消息能否转发给该队列
                    // FANOUT，所有绑定的队列都要转发
                    // TOPIC，需要判定下 bindingKey 和 routingKey 是否匹配
                    if (!router.route(exchange.getType(), binding, message)) {
                        continue;
                    }
                    // 4) 真正转发给队列
                    sendMessage(queue, message);
                }
            }
            return true;
        } catch (Exception e) {
            System.out.println("[VirtualHost] 消息发送失败！");
            e.printStackTrace();
            return false;
        }
    }

    private void sendMessage(MSGQueue queue, Message message) throws IOException, MqException, InterruptedException {
        // 把消息写到硬盘
        int deliverMode = message.getDeliverMode();
        // deliverMode 为 0x1 不持久化，0x2 持久化
        if (deliverMode == 2) {
            diskDataCenter.sendMessage(queue, message);
        }
        // 写入内存
        memoryDataCenter.sendMessage(queue, message);
        // 通知消费者可以消费了
        consumerManager.notifyConsume(queue.getName());
    }


    // 订阅消息
    // 添加一个队列的订阅者，当队列收到消息之后，就要把消息推送给对应的消费者
    // consumerTag 消费者的身份标识
    // autoAck 消息被消费完成后，应答的方式为 true，则自动应答，false，需要手动应答
    // Consumer 是一个回调函数，此处类型设置为函数式接口，这样后续调用 basicConsume 并且传实参的时候，就可以写作 lambda 的样子
    public boolean basicConsume(String consumerTag, String queueName, boolean autoAck, Consumer consumer) {
        // 构造一个 ConsumerEnv对象，把这个对应的队列找到，再把这个 Consumer对象 添加到该队列中
        System.out.println();
        System.out.println();
        System.out.println(queueName);
        queueName = virtualHostName + queueName;
        System.out.println();
        System.out.println(virtualHostName);
        System.out.println(queueName);
        System.out.println();
        System.out.println();
        try {
            consumerManager.addConsumer(consumerTag, queueName, autoAck, consumer);
            System.out.println("[VirtualHost] basicConsume 成功！queueName=" + queueName);
            return true;
        } catch (Exception e) {
            System.out.println("[VirtualHost] basicConsume 失败！queueName=" + queueName);
            e.printStackTrace();
            return false;
        }
    }

    public boolean basicAck(String queueName, String messageId) {
        queueName = virtualHostName + queueName;
        try {
            // 1. 获取到消息和队列
            Message message = memoryDataCenter.getMessage(messageId);
            if (message == null) {
                throw new MqException("[VirtualHost] 要确认的消息不存在！messageId=" + messageId);
            }
            MSGQueue queue = memoryDataCenter.getQueue(queueName);
            if (queue == null) {
                throw new MqException("[VirtualHost] 要确认的队列不存在！queueName=" + queueName);
            }
            // 2. 删硬盘
            if (message.getDeliverMode() == 2) {
                diskDataCenter.deleteMessage(queue, message);
            }
            // 3. 删消息中心的数据
            memoryDataCenter.removeMessage(messageId);
            // 4. 删待确认集合中的数据
            memoryDataCenter.removeMessageWaitAck(queueName, messageId);
            System.out.println("[VirtualHost] basicAck 成功！消息被确认成功！queueName=" + queueName +
                    "，messageId=" + messageId);
            return true;
        } catch (Exception e) {
            System.out.println("[VirtualHost] basicAck 成功！消息被确认成功！queueName=" + queueName +
                    "，messageId=" + messageId);
            e.printStackTrace();
            return false;
        }
    }
}
